<script setup>
import { useStore } from 'vuex'
import { ref, onMounted, inject, watch, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import EmojiPicker from 'vue3-emoji-picker'
import 'vue3-emoji-picker/css'
const store = useStore()
const username = ref(store.state.userStore.userInfo.username)
const avatarUrl = ref(store.state.userStore.userInfo.avatarUrl)
const groupname = ref(inject('groupName'))
const content = ref()
const contents = ref()
const count = ref(0)
const { proxy } = getCurrentInstance()
const socket = ref(proxy.$webSocketService.socket)
const ifhistory = ref(false)
const historymsg = ref([])
const fileurl = ref('')
const params = ref({
  key: '',
  username: username.value,
  touser: groupname.value
})
onMounted(() => {

})

const msg = ref({
  content,
  username,
  groupname,
  avatarUrl,
  type: 'text',
  chattype: 'Group'
})

const backmsgAndsendmsg = ref([])
const previousValues = ref([])
const previousValue = ref(null)
const showEmoji = ref(false)
const serverurl = ref('api/groupmsgcontroller/getfile')

socket.value.addEventListener('message', (res) => {
  if ((res.data) !== '用户不在线' && JSON.parse(res.data).chattype === 'Group') {
    backmsgAndsendmsg.value.push(JSON.parse(res.data))
  }
})

const send = () => {
  if (content.value === null) {
    ElMessage.error('输入不能为空')
  } else {
    content.value = contents.value
    socket.value.send(JSON.stringify(msg.value))
    backmsgAndsendmsg.value.push({ ...msg.value })
    contents.value = null
  }
}
const handleKeyUp = (e) => {
  if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 65 && e.keyCode <= 90) || e.keyCode === 8) {
    // 用户输入的字符，需要自动补全
    search()
  } else if (e.keyCode === 13) {
    // 用户按回车，需要搜索
    search()
  }
}
const search = () => {
  axios.post('api/groupmsgcontroller/list', {
    key: params.value.key,
    username: username.value,
    touser: groupname.value
  }).then(res => {
    historymsg.value = res.data.groupMessagesList
  })
}
const history = () => {
  ifhistory.value = true
  search()
}
const cancelClick = () => {
  ifhistory.value = false
  params.value.key = ''
}

const insertemoji = (emoji) => {
  contents.value = contents.value + emoji.i
}

const emo = () => {
  showEmoji.value = true
}

const fileinfoback = (res) => {
  if (res !== null) {
    console.log(res)
    msg.value.content = res[0]
    msg.value.type = 'file'
    socket.value.send(JSON.stringify(msg.value))
    backmsgAndsendmsg.value.push({ ...msg.value })
    fileurl.value = res[1]
  }
}

const upload = async () => {
  const response = await fetch(fileurl)
  const blob = await response.blob()
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = msg.value.content
  link.click()
}
watch(
  () => groupname.value,
  (newVal, oldVal) => {
    if (oldVal !== undefined) {
      previousValue.value = oldVal
      console.log(previousValue.value)
      if (backmsgAndsendmsg.value.length !== 0) {
        count.value++
        // 如果监听的值不是之前出现过的某个值，则将当前值存储到 sessionStorage 中
        sessionStorage.setItem(count.value + previousValue.value, JSON.stringify(backmsgAndsendmsg.value))
        // 同时将当前值加入 previousValues 数组中
        previousValues.value.push(previousValue.value)
        backmsgAndsendmsg.value = []
        contents.value = ''
      }
      if (previousValues.value.includes(groupname.value)) {
        // 如果监听的值是之前出现过的某个值，则从 sessionStorage 中获取以 touser 开头的键值对
        const keys = Object.keys(sessionStorage).filter(key => key.endsWith(groupname.value))

        const length = keys.length - 1
        const values = JSON.parse(sessionStorage.getItem(keys[length]))
        for (let i = 0; i < values.length; i++) {
          backmsgAndsendmsg.value.push(values[i])
        }
      }
    }
  }
)
</script>

<template>
  <div class="chathead">{{ groupname }}</div>
  <el-main class="chatmain">
    <div class="message" v-for="(messages, index) in backmsgAndsendmsg" :key="index">
      <div v-show="messages.username !== username && messages.chattype === 'Group'" class="msgleft">
        <div class="imgleft"><img :src="'src/' + messages.avatarUrl" class="diog-friend-img" ref="img" /></div>
        <div class="usernameleft">{{ messages.username }}
          <div class="diogleft">{{ messages.content }}</div>
        </div>
        <div class="iffileleft" v-show="messages.type == 'file'" @click="upload">
          <el-icon>
            <Download />
          </el-icon>
        </div>
      </div>
      <div v-show="messages.username === username && messages.chattype === 'Group'" class="msgright">
        <div class="iffileright" v-show="messages.type == 'file'" @click="upload">
          <el-icon>
            <Download />
          </el-icon>
        </div>
        <div class="usernameright">{{ username }}
          <div class="diogright">{{ messages.content }}</div>
        </div>
        <div class="imgright"><img :src="'src/' + avatarUrl" class="diog-friend-img" ref="img" /></div>
      </div>
    </div>
  </el-main>
  <div class="util">
    <div class="utilleft">
      <div class="emo" @click="emo">

        <el-popover placement="top" :width="280" trigger="click">
          <template #reference>
            <el-button style="margin-right: 16px">
              <el-icon>
                <ElementPlus />
              </el-icon>
            </el-button>
          </template>
          <div>
            <EmojiPicker @select="insertemoji" :native="true" :mode="prepend"></EmojiPicker>
          </div>
        </el-popover>

      </div>
      <div class="file" @click="file">

        <el-popover placement="top" :width="363" trigger="click">
          <template #reference>
            <el-button style="margin-right: 16px">
              <el-icon>
                <Folder />
              </el-icon>
            </el-button>
          </template>
          <div>
            <el-upload class="upload-demo" drag :action='serverurl' multiple :data="filemsg" :on-success="fileinfoback">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                Drop file here or <em>click to upload</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  jpg/png files with a size less than 500kb
                </div>
              </template>
            </el-upload>
          </div>
        </el-popover>

      </div>
    </div>
    <div class="utilright" @click="history"><el-icon>
        <Clock />
      </el-icon>
    </div>
    <el-drawer v-model="ifhistory" direction="rtl" size="35%" :with-header="false" :before-close="handleClose">
      <div class="historytitle">
        <div class="historytitleleft">聊天记录</div>
        <div class="historytitleright"><input type="text" v-model="params.key" title="请输入关键字"
            @keyup="handleKeyUp($event)"><button @click="handleSearch">搜索</button></div>
      </div>

      <el-tabs type="border-card">

        <el-tab-pane label="全部">
          <div>
            <el-timeline>
              <el-timeline-item v-for="(msg, index) in historymsg" :key="index" :timestamp="msg.sendTime" placement="top">
                {{ msg.fromUser }}： {{ msg.content }}
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-tab-pane>
        <el-tab-pane label="图片">图片</el-tab-pane>
        <el-tab-pane label="文件">文件</el-tab-pane>

      </el-tabs>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">cancel</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
  <el-footer class="chatfooter">
    <el-input v-model="contents" :rows="10" type="textarea" placeholder="请输入内容" @keyup.enter="send"></el-input>
    <div class="button"><button @click="send">发送</button></div>
  </el-footer>
</template>

<style scoped>
.chathead {
  height: 30px;
  text-align: left;
  border-bottom: solid 0.5px rgba(0, 0, 0, 0.197);

}

.chatmain {
  border-bottom: solid 0.5px rgba(0, 0, 0, 0.197);
  height: 400px;
}

.button {

  text-align: right;
  color: #124280;
}

.message {
  width: auto;
  height: 50px;

}

.msgleft {
  display: flex;
}

.usernameleft {
  text-align: left;
  padding-left: 2px;
  margin-top: 1px;
  display: inline;
  font-size: small;
}

.diogleft {
  padding-top: 5px;
  padding-bottom: 5px;
  border: solid black 0.5px;
  border-radius: 5px;
  text-align: left;
  background-color: rgb(129, 191, 218);
}

.iffileleft {
  height: 10px;
  background-color: beige;
  margin-top: 20px;
  padding-bottom: 5px;
  padding-left: 5px;
  padding-right: 5px;
  text-align: left;
  border-radius: 50px;
}

.msgright {
  display: flex;
  justify-content: right;
}

.diogright {
  padding-top: 5px;
  padding-bottom: 5px;
  border: solid black 0.5px;
  border-radius: 5px;
  text-align: left;
  background-color: rgb(129, 191, 218);
}

.iffileright {
  height: 10px;
  background-color: beige;
  margin-top: 20px;
  padding-bottom: 5px;
  padding-left: 5px;
  padding-right: 5px;
  text-align: right;
  border-radius: 50px;
}

.usernameright {
  display: inline;
  text-align: right;
  padding-right: 2px;
  margin-top: 1px;
  font-size: small;
}

.imgright {
  display: inline;
}

.util {
  display: flex;
  border-bottom: solid rgba(0, 0, 0, 0.121) 0.5px;
  justify-content: space-between;
}

.util .utilleft {
  display: flex;
}

.emo {
  margin-top: 2px;
  padding-right: 10px;
  font-size: 20px;
}

.file {
  padding-top: 2px;
  padding-right: 10px;
  font-size: 20px;
}

.utilright {
  padding-top: 2px;
  padding-right: 10px;
  font-size: 20px;
}

.historytitle {
  display: flex;
  padding: 0 0 0 0;
  text-align: left;
  border-bottom: solid rgba(0, 0, 0, 0.121) 0.5px;
  padding-bottom: 10px;
}

.historytitleleft {
  padding-right: 50px;
}
</style>
